package com.mikhailenko.transportMVC.service.es.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mikhailenko.transportMVC.exeption.es.RuleDBNotFoundException;
import com.mikhailenko.transportMVC.model.es.RuleDB;
import com.mikhailenko.transportMVC.repository.es.RuleRepository;
import com.mikhailenko.transportMVC.service.es.RuleService;

@Service
public class RuleServiceImpl implements RuleService {

    @Autowired
    private RuleRepository ruleRepository;
    
    @Override
    public RuleDB create(RuleDB ruleDB) {
        RuleDB createdRule = ruleDB;
        return ruleRepository.saveAndFlush(createdRule);
    }

    @Override
    public RuleDB delete(int id) throws RuleDBNotFoundException {
        RuleDB deletedRule = ruleRepository.findOne(id);
        
        if ( deletedRule == null ){
            throw new RuleDBNotFoundException();
        }
        
        ruleRepository.delete(deletedRule);
        return deletedRule;
    }

    @Override
    public List<RuleDB> findAll() {
        return ruleRepository.findAll();
    }

    @Override
    public RuleDB update(RuleDB ruleDB) throws RuleDBNotFoundException {
        RuleDB updatedRule = ruleRepository.findOne(ruleDB.getId());
        
        if (updatedRule == null){
            throw new RuleDBNotFoundException();
        }
        
        updatedRule.setInputs(ruleDB.getInputs());
        updatedRule.setResult(ruleDB.getResult());
        updatedRule.setBlock(ruleDB.getBlock());
        
        return updatedRule;
    }

    @Override
    public RuleDB findById(int id) {
        return ruleRepository.findOne(id);
    }

	@Override
	public List<RuleDB> findByBlockId(int id) {
		return ruleRepository.findByBlockId(id);
	}

}
